<template>
	<view class="container" :data-theme="theme">
		<view class="header">
			<view class="header-title">
				<view class="title-left">仓库：{{ticketInfo.depotName}}</view>
				<!-- <view class="title-right">2024.3.20</view> -->
			</view>
		</view>
		<view class="content">
			<!-- 这里是可滚动的内容 -->
			<scroll-view class="scroll-view" scroll-y>
				<view class="scroll-view-inner-card-item">
					<view class="card-list">
						<!-- 商品信息 -->
						<view class="outer">
							<view class="outer-card-item">
								<image :src="ticketInfo.iconUrl" mode="" class="outer-left"></image>
								<view class="outer-right">
									<view class="">
										{{ticketInfo.productName}}
									</view>
									<view>{{ticketInfo.attrName}}</view>
								</view>
							</view>
						</view>
						<!-- end -->
						<!-- 上传信息 -->
						<view class="inner">
							<view class="inner-card-item" v-for="(item,index) in ticketInfo.ticketinfoMap" :key="index">

								<view class="inner-left">
									<view class="inner-left-top"> 第三方检测报告</view>
									<view class="inner-left-bottom"><span
											:style="{color:bgColor}">{{item.typeName}}</span>
									</view>
								</view>
								<view class="inner-right">
									<uni-forms :modelValue="item" :ref="'uploadRefs' + index" :rules="uploadRules">
										<uni-forms-item name="selectDateTypeName">
											<view class="inner-right-top">
												<view
													style="display: flex;flex-flow: row;margin-right: 20rpx;flex-direction: column;width: 240rpx;">
													<picker @change="frameUpChange($event,index)"
														@cancel="frameUpCancel(index)" @click="frameUpClick(index)"
														:value="item.indateIndex" :range="indateList" range-key="name"
														style="display: flex;" :color="bgColor">
														<view style="display: flex;">
															<view style="font-size: 13px;margin-right: 6rpx;"
																v-if="item.indateIsShow">
																请选择有效期类型 </view>
															<view style="font-size: 13px;margin-right: 6rpx;" v-else>
																{{ item.selectDateTypeName }}
															</view>
															<u-icon
																:name="item.indateArrowsIsShow ? 'arrow-down-fill' : 'arrow-up-fill'"
																size="12"></u-icon>
														</view>
													</picker>
												</view>
												<!-- 到期日  长期有效 -->
												<view v-if="item.indateIndex == 0 || item.indateIndex == 2">
													<picker mode="date" :value="date" fields="day"
														@change="bindDateChange($event,index)" @click="dateClick(index)"
														@cancel="cancelClick(index)">
														<view style="display: flex;align-items: center;">
															<view class="uni-input">
																{{item.selectDateType == 1 ? item.endDate : item.selectDateType == 3 ? item.startDate : ''}}
															</view>
															<u-icon
																:name="item.arrow ? 'arrow-down-fill' : 'arrow-up-fill'"
																size="12"></u-icon>
														</view>
													</picker>
												</view>
												<!-- 签发/年审日 -->

											</view>
										</uni-forms-item>
										<view v-if="item.indateIndex== 1" style="padding-top: 10rpx;">
											<uni-forms-item name="assignDate">
												<uni-datetime-picker v-model="item.assignDate" type="daterange"
													:border="false" @change="changeAssignDate($event,index)">
												</uni-datetime-picker>
											</uni-forms-item>
										</view>
										<uni-forms-item name="content">

											<view class="inner-right-bottom">
												<view class="bottom-title">
													请对照图片示例要求上传，避免因不符合要求而驳回。<span
														class="title-instance">查看以下示例、常见驳回案例</span>
												</view>
												<view class="bottom-img">
													<image :src="cur.url" v-for="(cur,index2) in imageList"
														:key="index2" @click="previewImage(index2)"></image>
													<u-upload :fileList="item.content" @afterRead="afterRead"
														@delete="deletePic" :name="item.imageIndex" multiple
														:maxCount="4">
													</u-upload>



												</view>
												<view class="bottom-text">第三方检测机构出具的本商品检测报告，请上传<span
														class="page-num">全部页数</span> </view>
											</view>
										</uni-forms-item>
									</uni-forms>
								</view>
							</view>
							<!-- end -->
						</view>
						<!-- end -->

					</view>
				</view>
				<u-empty v-if="false" text="暂无票证" style="height: 100%;"
					icon="http://cdn.uviewui.com/uview/empty/data.png"></u-empty>
			</scroll-view>

		</view>
		<view class="footer">
			<button class="footer-button" @click="confirmUpload">确认上传</button>
		</view>
	</view>
</template>
<script>
	import {
		setThemeColor
	} from '../../../utils/setTheme';
	import {
		updateTicketUploadApi
	} from "@/api/ticketUpload.js"
	let app = getApp()
	export default {
		data() {
			return {
				bgColor: '#fff',
				theme: app.globalData.theme,
				// -------------------有效期搜索----------------------
				// 有效期列表
				indateList: [{
						name: "到期日",
						value: "1"
					}, {
						name: "签发日-到期日",
						value: "2"
					},
					{
						name: "长期有效",
						value: "3"
					}
				],
				date: '',
				// 示例图
				imageList: [{
					url: "http://img30.360buyimg.com/popWaterMark/jfs/t1/129817/18/27106/65764/632bc467E3f94c37d/3cb67ddb8332ac70.jpg"
				}, {
					url: "http://img30.360buyimg.com/popWaterMark/jfs/t1/129817/18/27106/65764/632bc467E3f94c37d/3cb67ddb8332ac70.jpg"
				}, {
					url: "http://img30.360buyimg.com/popWaterMark/jfs/t1/129817/18/27106/65764/632bc467E3f94c37d/3cb67ddb8332ac70.jpg"
				}, ],
				// 校验上传图片
				uploadRules: {
					content: {
						rules: [{
							required: true,
							errorMessage: "请上传图片"
						}]
					},
					selectDateTypeName: {
						rules: [{
							required: true,
							errorMessage: "请选择有效期类型"
						}]
					},
					assignDate: {
						rules: [{
							required: true,
							errorMessage: "请选择日期"
						}]
					},


				},
				// 票证信息
				ticketInfo: {},
				// 签发年审日指定日期
				assignDate: '', //
			}
		},
		onLoad(options) {
			this.bgColor = setThemeColor()
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.bgColor,
			});
			// 获取上个页面的值
			if (options && options.ticketInfo) {
				this.ticketInfo = JSON.parse(options.ticketInfo)
			}
			this.date = this.getDate()

		},
		methods: {
			// ---------------------关于待装筐搜索日期事件------------------------------
			// 待装筐搜索事件
			frameUpChange(event, index) {
				// 设置每一个检测报告的有效期类型
				this.$set(this.ticketInfo.ticketinfoMap[index], 'selectDateTypeName', this.indateList[event.detail.value]
					.name)

				this.$set(this.ticketInfo.ticketinfoMap[index], 'selectDateType', this.indateList[event.detail.value]
					.value)
				// 有效期索引值
				this.$set(this.ticketInfo.ticketinfoMap[index], 'indateIndex', event.detail.value)

				// 展示有效期
				this.$set(this.ticketInfo.ticketinfoMap[index], 'indateIsShow', false)
				// 改变有效期的箭头
				this.$set(this.ticketInfo.ticketinfoMap[index], 'indateArrowsIsShow', false)
				// 设置有效期的时间
				if (this.ticketInfo.ticketinfoMap[index].selectDateType == 1) {
					this.$set(this.ticketInfo.ticketinfoMap[index], 'endDate', this.date)
					this.$set(this.ticketInfo.ticketinfoMap[index], 'startDate', null)
				} else if (this.ticketInfo.ticketinfoMap[index].selectDateType == 3) {
					console.log("this.date", this.date)
					this.$set(this.ticketInfo.ticketinfoMap[index], 'startDate', this.date)
					this.$set(this.ticketInfo.ticketinfoMap[index], 'endDate', null)
				}

			},
			// 待装筐取消事件
			frameUpCancel(index) {
				// 改变有效期的箭头
				this.$set(this.ticketInfo.ticketinfoMap[index], 'indateArrowsIsShow', false)
			},
			// 待装筐点击事件
			frameUpClick(index) {
				// 改变有效期的箭头
				this.$set(this.ticketInfo.ticketinfoMap[index], 'indateArrowsIsShow', true)
			},
			// -------------------选择到期时间-------------------


			// 获取当前月份
			getDate() {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				month = month > 9 ? month : '0' + month;
				let day = date.getDate();
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			// 改变日期
			bindDateChange(event, index) {
				this.date = event.detail.value
				// 改变日期的箭头
				this.$set(this.ticketInfo.ticketinfoMap[index], 'arrow', false)
				// 设置有效期的时间
				if (this.ticketInfo.ticketinfoMap[index].selectDateType == 1) {
					this.$set(this.ticketInfo.ticketinfoMap[index], 'startDate', null)
					this.$set(this.ticketInfo.ticketinfoMap[index], 'endDate', event.detail.value)
				} else if (this.ticketInfo.ticketinfoMap[index].selectDateType == 3) {
					this.$set(this.ticketInfo.ticketinfoMap[index], 'startDate', event.detail.value)
					this.$set(this.ticketInfo.ticketinfoMap[index], 'endDate', null)
				}

			},
			// 点击日期改变箭头方向
			dateClick(index) {
				// 改变日期的箭头
				this.$set(this.ticketInfo.ticketinfoMap[index], 'arrow', true)
			},
			// 取消日期的事件
			cancelClick(index) {
				// 改变日期的箭头
				this.$set(this.ticketInfo.ticketinfoMap[index], 'arrow', false)
			},
			// 签发/年审日期选择
			changeAssignDate(event, index) {
				this.assignDate = event[0] + '-' + event[1]
				this.$set(this.ticketInfo.ticketinfoMap[index], 'startDate', event[0])
				this.$set(this.ticketInfo.ticketinfoMap[index], 'endDate', event[1])
			},
			// ------------------图片预览-------------------------
			previewImage(index) {
				uni.previewImage({
					current: index,
					urls: this.imageList.map(item => item.url)
				})
			},
			//  -----------------------------上传图片--------------------------------
			// 删除图片
			deletePic(event) {
				this.ticketInfo.ticketinfoMap[Number(event.name) - 1][`content`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.ticketInfo.ticketinfoMap[Number(event.name) - 1][`content`]
					.length
				lists.map((item) => {
					this.ticketInfo.ticketinfoMap[Number(event.name) - 1][`content`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					if (result == null) {
						uni.showToast({
							title: "上传失败",
							icon: "none",
						})
						this.deletePic(event.index, 1);
						break;
					}
					let newStatus = {
						status: 'success',
						message: '上传成功',
						url: result,
					}
					let item = this.ticketInfo.ticketinfoMap[Number(event.name) - 1][`content`][
						fileListLen
					]

					this.ticketInfo.ticketinfoMap[Number(event.name) - 1][`content`].splice(
						fileListLen, 1, Object
						.assign(item,
							newStatus))
					fileListLen++
				}
			},
			uploadFilePromise(filePath) {
				return this.$util.uploadFilePromise(filePath, {
					url: 'upload/image',
					name: "multipart", //固定 multipart
					model: "product", //模块 用户user,商品product,微信wechat,news文章
					pid: 1, //分类ID 0编辑器,1商品图片,2拼团图片,3砍价图片,4秒杀图片,5文章图片,6组合数据图,7前台用户,8微信系列
					count: 1
				});
				// 修改商户入驻申请信息
			},
			// 确认上传图片
			async confirmUpload() {

				let validate = 0
				// 循环遍历所有的校验
				for (let i = 0; i < this.ticketInfo.ticketinfoMap.length; i++) {
					this.$refs['uploadRefs' + i][0].validate().then(res => {
						validate++
						// 全部校验完
						if (validate == this.ticketInfo.ticketinfoMap.length) {
							uni.showModal({
								title: '提示',
								content: '是否确定上传？',
								success: (res) => {
									if (res.confirm == true) {
										this.handleConfirm()
									} else {
										uni.showToast({
											title: '已取消上传',
											icon: 'none',
											duration: 1500
										})
									}
								}
							})
						}
					}).catch(err => {
						uni.showToast({
							title: '请完成校验',
							icon: "none",
							duration: 1500
						});
					})
				}

			},
			async handleConfirm() {
				let that = this
				let data = {}
				data.depotId = this.ticketInfo.depotId
				data.productId = this.ticketInfo.productId
				data.groupId = this.ticketInfo.groupId
				data.attrValueId = this.ticketInfo.ticketinfoMap[0].attrId
				data.ticketInfos = []
				let ticketInfoList = this.ticketInfo.ticketinfoMap.map(item => {
					return {
						id: item.id,
						type: item.type,
						content: item.content.map(cur => cur.url).join(','),
						groupId: item.groupId,
						attrId: item.attrId,
						selectDateType: item.selectDateType,
						endDate: item.endDate,
						startDate: item.startDate,
					}
				})
				data.ticketInfos.push({
					ticketInfos: ticketInfoList
				})
				console.log("data", data)
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				try {
					let res = await updateTicketUploadApi(data)
					if (res.code == 200) {
						if (res.data) {
							let tip = ''
							if (that.ticketInfo.proceedOrHistoryType == 1) {
								tip = "上传成功,点击确认返回票证上传页面"
							} else if (that.ticketInfo.proceedOrHistoryType == 2) {
								tip = '上传成功，点击确认返回历史票证页面'
							}

							uni.showModal({
								title: '提示',
								content: `${tip}`,
								showCancel: false,
								success: (res) => {
									if (res.confirm == true) {
										uni.navigateBack({
											delta: 1,
											success() {
												// 历史2  进行1
												if (that.ticketInfo.proceedOrHistoryType == 1) {
													const pages = getCurrentPages()
													const prePage = pages[pages.length - 2]
													// prePage.handleProceedUpload(true)
												} else if (that.ticketInfo.proceedOrHistoryType ==
													2) {
													const pages = getCurrentPages()
													const prePage = pages[pages.length - 2]
													console.log("pages", pages)
													prePage.historyTicketLook()
												}

											}
										});
									}
								}
							})


						} else {
							uni.showToast({
								title: '上传失败',
								icon: "none",
								duration: 1500
							});
						}

					} else {
						uni.showToast({
							title: res.message,
							icon: "none",
							duration: 1500
						});
					}
					uni.hideLoading()
				} catch (e) {
					//TODO handle the exception
					uni.hideLoading()
					uni.showToast({
						title: e,
						icon: 'none',
						duration: 1500
					})
				}
			},

		}

	}
</script>
<style lang="scss" scoped>
	page {
		height: 100%;


	}

	::v-deep .uni-forms-item {
		margin-bottom: 10px;
	}

	.container {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.header {
		.header-title {
			display: flex;
			justify-content: space-between;
			margin-top: 10rpx;
			padding: 30rpx;
			font-weight: bold;
		}
	}

	.content {
		flex: 1;
		overflow: hidden;
	}

	.scroll-view {
		height: 100%;
	}

	.scroll-view-inner-card-item {
		.card-list {
			display: flex;
			flex-direction: column;
			background-color: #fff;
			padding: 15rpx;
			margin: 0rpx 15rpx;
			margin-bottom: 20rpx;
			border-radius: 10rpx;

			// 外部内容
			.outer {
				.outer-card-item {
					display: flex;
					align-items: center;
					margin-bottom: 20rpx;
					line-height: 40rpx;

					.outer-left {
						width: 80rpx;
						height: 80rpx;
						margin-right: 20rpx;
					}
				}
			}

			// 内部内容
			.inner {
				.inner-card-item {
					margin-top: 2 0rpx;
					padding: 20rpx 10rpx;
					background-color: #f9f7ff;
					display: flex;

					.inner-left {
						display: flex;
						flex-direction: column;
						line-height: 33rpx;
						width: 210rpx;
						font-size: 26rpx;
						flex-shrink: 0;

						.inner-left-top {
							margin-bottom: 10rpx;
						}

					}

					.inner-right {
						display: flex;
						flex-direction: column;
						justify-content: center;

						.inner-right-top {
							display: flex;
							align-items: center;
							font-size: 26rpx;
						}

						.inner-right-bottom {
							padding: 20rpx 0;

							.bottom-title {
								font-size: 26rpx;
								line-height: 30rpx;

								.title-instance {
									color: #fe5c2d;
								}
							}

							.bottom-img {
								display: flex;
								flex-wrap: wrap;
								margin: 20rpx 0;

								image {
									width: 140rpx;
									height: 140rpx;
									margin-right: 15rpx;
									margin-bottom: 15rpx;
								}
							}

							.bottom-text {
								font-size: 26rpx;
								line-height: 30rpx;

								.page-num {
									color: #fe5c2d;
								}
							}
						}
					}
				}
			}

		}
	}

	.footer {
		.footer-button {
			@include main_bg_color(theme) padding: 20rpx;
			margin: 20rpx;
			color: white;

		}
	}
</style>